﻿using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using Newtonsoft.Json;

namespace DemoApp
{
    /// <summary>
    /// Interaction logic for PopUpListWindow.xaml
    /// </summary>
    public partial class PopupListWindow : Window
    {
        private int selectedComponent;

        public PopupListWindow(Dictionary<int, string> componentList)
        {
            Resources["ComponentList"] = componentList;
            InitializeComponent();
            
            selectedComponent = ((KeyValuePair<int, string>)lvComponentList.SelectedItem).Key;
            string result = WebServiceHelper.ConsumeWebService(
                "http://xman-ws.herokuapp.com/services/atomic/getmethods/" + selectedComponent);
            dynamic stuff = JsonConvert.DeserializeObject(result);
            lvMethodList.ItemsSource = JsonConvert.DeserializeObject<List<string>>(stuff.message.ToString());
        }

        private void Load_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = true;
            this.Close();
        }

        private void Execute_Click(object sender, RoutedEventArgs e)
        {
            var messageBoxService = ApplicationServicesProvider.Instance.Provider.MessageBoxService;
            if (lvMethodList.SelectedItem != null)
                messageBoxService.ShowInformation(
                    WebServiceHelper.ConsumeWebService("http://xman-ws.herokuapp.com/services/atomic/run/" + 
                    selectedComponent + "/" + lvMethodList.SelectedItem.ToString()));
            else
                messageBoxService.ShowInformation("Please select a method to execute..");
        }

        private void lvComponentList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                this.selectedComponent = ((KeyValuePair<int, string>)lvComponentList.SelectedItem).Key;
                string result = WebServiceHelper.ConsumeWebService(
                    "http://xman-ws.herokuapp.com/services/atomic/getmethods/" + selectedComponent);
                dynamic stuff = JsonConvert.DeserializeObject(result);
                lvMethodList.ItemsSource = JsonConvert.DeserializeObject<List<string>>(stuff.message.ToString());
            }
            catch (Exception) { }
        }

        public int getSelectedComponent()
        {
            return this.selectedComponent;
        }
    }
}
